package net.sf.l2j.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;

import net.sf.l2j.Config;
import net.sf.l2j.database.L2DatabaseFactory;
import net.sf.l2j.gameserver.datatables.CharNameTable;
import net.sf.l2j.gameserver.datatables.NpcTable;
import net.sf.l2j.gameserver.datatables.SpawnTable;
import net.sf.l2j.gameserver.model.L2ItemInstance;
import net.sf.l2j.gameserver.model.L2Spawn;
import net.sf.l2j.gameserver.model.L2World;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.MagicSkillUser;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
import net.sf.l2j.gameserver.templates.L2NpcTemplate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PcAction 
{
	private static final String UPDATE_PREMIUMSERVICE = "UPDATE character_premium SET premium_service=?,enddate=? WHERE account_name=?";
	private static Log _log = LogFactory.getLog(PcAction.class.getName());

	public static void addPremiumServices(int Months, String AccName) 
	{
		Connection con = null;
		try 
		{
			final Calendar finishtime = Calendar.getInstance();
			finishtime.setTimeInMillis(System.currentTimeMillis());
			finishtime.set(Calendar.SECOND, 0);
			finishtime.add(Calendar.MONTH, Months);

			con = L2DatabaseFactory.getInstance().getConnection();
			final PreparedStatement statement = con.prepareStatement(UPDATE_PREMIUMSERVICE);
			statement.setInt(1, 1);
			statement.setLong(2, finishtime.getTimeInMillis());
			statement.setString(3, AccName);
			statement.execute();
			statement.close();
		} 
		catch (SQLException e) 
		{
			_log.info("PremiumService: Could not increase data");
		} 
		finally 
		{
			try 
			{
				con.close();
			} 
			catch (SQLException e)
			{
			}
		}
	}

	public static void storeCharSex(L2PcInstance player, int mode) 
	{
		L2PcInstance character = player;

		if (character == null)
			return;

		Connection con = null;
		try 
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE characters SET sex=? WHERE obj_Id=?");
			statement.setInt(1, character.getAppearance().getSex() ? 1 : 0);
			statement.setInt(2, character.getObjectId());
			statement.execute();
			statement.close();
			if (mode == 0)
				character.sendMessage("Вы изменили пол.");
		} 
		catch (SQLException e) 
		{
			_log.warn("StoreSex:  Could not save data");
		} 
		finally 
		{
			try 
			{
				if (con != null)
					con.close();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
	}

	public static void giveItems(L2PcInstance player, int itemId, int count)
	{
		L2PcInstance character = player;
		if (character == null)
			return;

		giveItems(character, itemId, count, 0);
	}

	public static void giveItems(L2PcInstance player, int itemId, int count,int enchantlevel) 
	{
		L2PcInstance character = player;

		if (character == null)
			return;

		if (count <= 0)
			return;

		L2ItemInstance item = character.getInventory().addItem("PcAction",
				itemId, count, character, character.getTarget());

		if (item == null)
			return;
		if (itemId == 57) 
		{
			SystemMessage msg = new SystemMessage(SystemMessageId.EARNED_ADENA);
			msg.addNumber(count);
			character.sendPacket(msg);
		} 
		else 
		{
			if (count > 1) 
			{
				SystemMessage msg = new SystemMessage(SystemMessageId.EARNED_S2_S1_S);
				msg.addItemName(item.getItemId());
				msg.addNumber(count);
				character.sendPacket(msg);
			} 
			else 
			{
				SystemMessage msg = new SystemMessage(SystemMessageId.EARNED_ITEM);
				msg.addItemName(item.getItemId());
				character.sendPacket(msg);
			}
		}
		character.getInventory().updateInventory(item);
	}

	public static void botMessage(L2PcInstance activeChar, L2PcInstance player) 
	{
		L2PcInstance character = activeChar;

		if (character == null)
			return;
		if (player == null)
			return;

		Connection con = null;
		PreparedStatement statement = null;
		try 
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement("INSERT INTO character_reports(char_name, bot_name, date) VALUES(?,?,now())");
			statement.setString(1, character.getName());
			statement.setString(2, player.getName());
			statement.executeUpdate();
		} 
		catch (Exception e)
		{
			_log.fatal("Could not write botReport:", e);
		} 
		finally 
		{
			try 
			{
				if (con != null)
					con.close();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
	}

	public static void changeName(L2PcInstance activeChar, String _name,String oldName)
	{
		L2PcInstance character = activeChar;

		if (character == null)
			return;

		if (CharNameTable.getInstance().doesCharNameExist(_name.toLowerCase())) 
		{
			character.sendMessage("Ник уже используется");
			return;
		} 
		else if (!Config.CNAME_PATTERN.matcher(_name).matches()) 
		{
			character.sendMessage("Не корректный ник");
			return;
		} 
		else 
		{
			character.destroyItemByItemId("ServiceManager",Config.Service_ChangeNick_PriceID,Config.Service_ChangeNick_PriceCount, character, true);
			L2World.getInstance().removeFromAllPlayers(character);
			character.setName(_name);
			character.store();
			L2World.getInstance().addToAllPlayers(character);
			character.broadcastUserInfo();
			if (character.isInParty())
				character.getParty().updatePartyMembersWindow();
			if (character.getClan() != null)
				character.getClan().broadcastClanStatus();
			character.sendMessage("Вы изменили ник");

			if (Config.SERVICE_AUDIT) 
			{
				String serviceName = "";
				serviceName = "change Name";
				String message = "";
				message = ("Change name from " + oldName + " to " + _name + ".");
				ServiceLog.ServiceAudit(character, serviceName, message);
			}
		}
	}

	public static void spawnCustomNpc(int _npcId, String title) 
	{
		L2NpcTemplate tmpl = NpcTable.getInstance().getTemplate(_npcId);
		try 
		{
			L2Spawn _npcSpawn = new L2Spawn(tmpl);
			_npcSpawn.setLocx(Config.Service_Spawn_X);
			_npcSpawn.setLocy(Config.Service_Spawn_Y);
			_npcSpawn.setLocz(Config.Service_Spawn_Z);
			_npcSpawn.setAmount(1);
			_npcSpawn.setHeading(1);
			_npcSpawn.setRespawnDelay(1);

			SpawnTable.getInstance().addNewSpawn(_npcSpawn, false);

			_npcSpawn.init();
			_npcSpawn.getLastSpawn().getStatus().setCurrentHp(999999999);
			_npcSpawn.getLastSpawn().setTitle(title);
			_npcSpawn.getLastSpawn().isAggressive();
			_npcSpawn.getLastSpawn().decayMe();
			_npcSpawn.getLastSpawn().spawnMe(_npcSpawn.getLastSpawn().getX(),
			_npcSpawn.getLastSpawn().getY(),
			_npcSpawn.getLastSpawn().getZ());
			_npcSpawn.getLastSpawn().broadcastPacket(new MagicSkillUser(_npcSpawn.getLastSpawn(), _npcSpawn.getLastSpawn(), 1034, 1, 1, 1));
		} 
		catch (Exception e) 
		{
			_log.error("Spawn serviceManager: " + e.getMessage());
		}
	}
}